package br.com.lumis.ims.service.cloud.processaction;

import java.util.Collection;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.group.GroupConfig;
import lumis.portal.manager.ManagerException;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.user.UserConfig;
import lumis.util.XmlUtil;
import lumis.util.log.ILogger;
import lumis.util.log.LoggerFactory;
import br.com.lumis.ims.service.cloud.dao.UserDAO;
import br.com.lumis.ims.service.cloud.util.ImsRequestParameters;

@SuppressWarnings("unchecked")
public class UserProcessActionHandler extends ProcessActionHandler<Source> {
	private static final ILogger LOGGER = LoggerFactory.getLogger(UserProcessActionHandler.class);
	

	private UserDAO userDAO = new UserDAO();

	@Override
	public void processAction() throws PortalException {
		String actionType = XmlUtil.readAttributeString(ImsRequestParameters.ACTIONTYPE, processActionNode, "");

		if (actionType.equals(ImsRequestParameters.USER_ADD))
			processAddUser();
	}

	/*
	 * Create object user in lum_user
	 */
	private void processAddUser() throws PortalException {
		try {
			String id = getParameter(ImsRequestParameters.ID, String.class);
			String name  = getParameter(ImsRequestParameters.NAME, String.class);
			String login = getParameter(ImsRequestParameters.LOGIN, String.class);
			String email = getParameter(ImsRequestParameters.EMAIL, String.class);
			String password = getParameter(ImsRequestParameters.PASSWORD, String.class);

			UserConfig userConfig = new UserConfig();
			userConfig.setId(id);
			userConfig.setFirstName(name);
			userConfig.setLogin(login);
			userConfig.setPassword(password);
			userConfig.setEmail(email);
			userConfig.setChannelId(ImsRequestParameters.CHANNEL_ID);

			String lumUserId = ManagerFactory.getUserManager().add(sessionConfig, userConfig, transaction);

			Collection<GroupConfig> groups = ManagerFactory.getGroupManager().getByChannelId(sessionConfig,ImsRequestParameters.CHANNEL_ID, transaction);

			for (GroupConfig groupConfig : groups) {
				if (groupConfig.getAlias().equals("ims.Clientes"))
					ManagerFactory.getGroupManager().addMember(sessionConfig,
							groupConfig.getId(), userConfig.getId(),
							transaction);
			}

			userDAO.updateLumUserId(name, lumUserId, transaction);

			addDefaultResponse();

		} catch (ManagerException e) {
			LOGGER.error(e);
			
		}
	}
}
